<?php
// 习题集和章节管理相关功能

// 处理习题集和章节的表单请求（必须在HTML输出前调用）
function handleExerciseSetsRequests($conn) {
    // 处理添加习题集的请求
    if (isset($_POST['add_exercise_set'])) {
        $name = $_POST['set_name'];
        $description = $_POST['set_description'];
        
        $stmt = $conn->prepare("INSERT INTO exercise_sets (name, description) VALUES (?, ?)");
        $stmt->bind_param("ss", $name, $description);
        $stmt->execute();
        $stmt->close();
        
        // 重定向到当前页面，避免表单重复提交
        header("Location: index.php?tab=exercise_sets");
        exit();
    }
    
    // 处理编辑习题集的请求
    if (isset($_POST['update_exercise_set'])) {
        $set_id = $_POST['update_set_id'];
        $name = $_POST['update_set_name'];
        $description = $_POST['update_set_description'];
        
        $stmt = $conn->prepare("UPDATE exercise_sets SET name = ?, description = ? WHERE id = ?");
        $stmt->bind_param("ssi", $name, $description, $set_id);
        $stmt->execute();
        $stmt->close();
        
        header("Location: index.php?tab=exercise_sets");
        exit();
    }

    // 处理添加章节的请求
    if (isset($_POST['add_chapter'])) {
        $exercise_set_id = $_POST['exercise_set_id'];
        $name = $_POST['chapter_name'];
        $description = $_POST['chapter_description'];
        
        $stmt = $conn->prepare("INSERT INTO chapters (exercise_set_id, name, description) VALUES (?, ?, ?)");
        $stmt->bind_param("iss", $exercise_set_id, $name, $description);
        $stmt->execute();
        $stmt->close();
        
        header("Location: index.php?tab=exercise_sets");
        exit();
    }
    
    // 处理编辑章节的请求
    if (isset($_POST['update_chapter'])) {
        $chapter_id = $_POST['update_chapter_id'];
        $name = $_POST['update_chapter_name'];
        $description = $_POST['update_chapter_description'];
        
        $stmt = $conn->prepare("UPDATE chapters SET name = ?, description = ? WHERE id = ?");
        $stmt->bind_param("ssi", $name, $description, $chapter_id);
        $stmt->execute();
        $stmt->close();
        
        header("Location: index.php?tab=exercise_sets");
        exit();
    }

    // 处理删除习题集的请求（级联删除章节和题目）
    if (isset($_POST['delete_set'])) {
        $set_id = $_POST['set_id'];
        
        // 开启事务
        $conn->begin_transaction();
        
        try {
            // 获取该习题集下的所有章节ID
            $chapter_result = $conn->query("SELECT id FROM chapters WHERE exercise_set_id = $set_id");
            $chapter_ids = [];
            while ($row = $chapter_result->fetch_assoc()) {
                $chapter_ids[] = $row['id'];
            }
            
            // 如果有章节，删除相关的记录
            if (!empty($chapter_ids)) {
                $chapter_ids_str = implode(',', $chapter_ids);
                $conn->query("UPDATE exam_records SET chapter_id = NULL WHERE chapter_id IN ($chapter_ids_str)");
            }
            
            // 删除该习题集下的所有章节
            $conn->query("DELETE FROM chapters WHERE exercise_set_id = $set_id");
            
            // 更新使用该习题集的记录
            $conn->query("UPDATE exam_records SET exercise_set_id = NULL WHERE exercise_set_id = $set_id");
            
            // 删除习题集
            $conn->query("DELETE FROM exercise_sets WHERE id = $set_id");
            
            // 提交事务
            $conn->commit();
        } catch (Exception $e) {
            // 回滚事务
            $conn->rollback();
        }
        
        header("Location: index.php?tab=exercise_sets");
        exit();
    }

    // 处理删除章节的请求（删除章节下的题目数据）
    if (isset($_POST['delete_chapter'])) {
        $chapter_id = $_POST['chapter_id'];
        
        // 开启事务
        $conn->begin_transaction();
        
        try {
            // 更新使用该章节的记录
            $conn->query("UPDATE exam_records SET chapter_id = NULL WHERE chapter_id = $chapter_id");
            
            // 删除章节
            $conn->query("DELETE FROM chapters WHERE id = $chapter_id");
            
            // 提交事务
            $conn->commit();
        } catch (Exception $e) {
            // 回滚事务
            $conn->rollback();
        }
        
        header("Location: index.php?tab=exercise_sets");
        exit();
    }
}

// 习题集和章节管理功能函数
function renderExerciseSetsManagement($conn) {

    // 获取所有习题集
    $sets_result = $conn->query("SELECT * FROM exercise_sets ORDER BY id");

    // 获取所有章节并按习题集分组
    $chapters_by_set = array();
    $chapters_result = $conn->query("SELECT c.*, e.name as set_name FROM chapters c LEFT JOIN exercise_sets e ON c.exercise_set_id = e.id ORDER BY e.id, c.id");
    while ($row = $chapters_result->fetch_assoc()) {
        if (!isset($chapters_by_set[$row['exercise_set_id']])) {
            $chapters_by_set[$row['exercise_set_id']] = array();
        }
        $chapters_by_set[$row['exercise_set_id']][] = $row;
    }

    // 开始构建HTML
    $html = '<div class="card">
        <div class="card-header">
            <h3>习题集管理</h3>
        </div>
        <div class="card-body">
        <!-- 添加习题集卡片 -->
        <div class="card mb-4">
            <div class="card-header">添加习题集</div>
            <div class="card-body">
                <form method="post">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="set_name" class="form-label">习题集名称</label>
                            <input type="text" class="form-control" id="set_name" name="set_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="set_description" class="form-label">描述</label>
                            <input type="text" class="form-control" id="set_description" name="set_description">
                        </div>
                    </div>
                    <button type="submit" name="add_exercise_set" class="btn btn-primary">添加习题集</button>
                </form>
            </div>
        </div>
        <!-- 添加章节卡片 -->
        <div class="card mb-4">
            <div class="card-header">添加章节</div>
            <div class="card-body">
                <form method="post">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label for="exercise_set_id" class="form-label">选择习题集</label>
                            <select class="form-select" id="exercise_set_id" name="exercise_set_id" required>
                                <option value="" disabled selected>请选择习题集</option>';
    
    // 添加习题集选项
    $sets_result->data_seek(0); // 重置结果集指针
    while ($set = $sets_result->fetch_assoc()) {
        $html .= "<option value='{$set['id']}'>{$set['name']}</option>";
    }
    
    $html .= '</select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="chapter_name" class="form-label">章节名称</label>
                            <input type="text" class="form-control" id="chapter_name" name="chapter_name" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="chapter_description" class="form-label">描述</label>
                            <input type="text" class="form-control" id="chapter_description">
                        </div>
                    </div>
                    <button type="submit" name="add_chapter" class="btn btn-primary">添加章节</button>
                </form>
            </div>
        </div>
        <!-- 习题集列表卡片 -->
        <div class="card">
            <div class="card-header">习题集列表</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>名称</th>
                                <th>描述</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>';
    
    // 添加习题集列表
    $sets_result->data_seek(0); // 重置结果集指针
    while ($set = $sets_result->fetch_assoc()) {
        $chapter_count = isset($chapters_by_set[$set['id']]) ? count($chapters_by_set[$set['id']]) : 0;
        $html .= "                                <tr>
                                    <td>{$set['id']}</td>
                                    <td>{$set['name']}</td>
                                    <td>{$set['description']}</td>
                                    <td>
                                        <div class='btn-group'>
                                            <button type='button' class='btn btn-sm btn-outline-primary' data-bs-toggle='collapse' data-bs-target='#chapters-{$set['id']}'>
                                                查看章节 ({$chapter_count})
                                            </button>
                                            <button type='button' class='btn btn-sm btn-outline-warning edit-set-btn' data-set-id='{$set['id']}' data-set-name='{$set['name']}' data-set-description='{$set['description']}'>
                                                编辑
                                            </button>
                                            <button type='button' class='btn btn-sm btn-outline-danger delete-set-btn' data-set-id='{$set['id']}' data-set-name='{$set['name']}'>
                                                删除
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <!-- 章节列表 -->
                                <tr id='chapters-{$set['id']}' class='collapse'>
                                    <td colspan='4'>
                                        <div class='bg-light p-3'>
                                            <h5>章节列表</h5>
                                            <div class='table-responsive'>
                                                <table class='table table-sm'>
                                                    <thead>
                                                        <tr>
                                                            <th>ID</th>
                                                            <th>章节名称</th>
                                                            <th>描述</th>
                                                            <th>操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>";
        
        if (isset($chapters_by_set[$set['id']])) {
            foreach ($chapters_by_set[$set['id']] as $chapter) {
                $html .= "                                                                <tr>
                                                                    <td>{$chapter['id']}</td>
                                                                    <td>{$chapter['name']}</td>
                                                                    <td>{$chapter['description']}</td>
                                                                    <td>
                                                                        <div class='btn-group'>
                                                                            <button type='button' class='btn btn-sm btn-outline-warning edit-chapter-btn' data-chapter-id='{$chapter['id']}' data-chapter-name='{$chapter['name']}' data-chapter-description='{$chapter['description']}'>
                                                                                编辑
                                                                            </button>
                                                                            <button type='button' class='btn btn-sm btn-outline-danger delete-chapter-btn' data-chapter-id='{$chapter['id']}' data-chapter-name='{$chapter['name']}'>
                                                                                删除
                                                                            </button>
                                                                        </div>
                                                                    </td>
                                                                </tr>";
            }
        } else {
            $html .= "                                                                <tr>
                                                                    <td colspan='4' class='text-center text-muted'>暂无章节</td>
                                                                </tr>";
        }
        
        $html .= "                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </td>
                                </tr>";
    }
    
    if ($sets_result->num_rows === 0) {
        $html .= "                                <tr>
                                    <td colspan='4' class='text-center text-muted'>暂无习题集</td>
                                </tr>";
    }
    
    $html .= "                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 删除确认表单 -->
    <form id='delete-form' method='post' style='display: none;'>
        <input type='hidden' name='set_id' id='delete-set-id'>
        <input type='hidden' name='chapter_id' id='delete-chapter-id'>
        <input type='hidden' name='delete_type' id='delete-type'>
    </form>
    
    <!-- 编辑习题集模态框 -->
    <div class='modal fade' id='editSetModal' tabindex='-1' aria-labelledby='editSetModalLabel' aria-hidden='true' data-bs-backdrop='static' data-bs-keyboard='false'>
        <div class='modal-dialog fixed-center'>
            <div class='modal-content'>
                <div class='modal-header'>
                    <h5 class='modal-title' id='editSetModalLabel'>编辑习题集</h5>
                    <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='关闭'></button>
                </div>
                <form id='edit-set-form' method='post'>
                    <input type='hidden' name='update_exercise_set' value='1'>
                    <input type='hidden' name='update_set_id' id='edit-set-id'>
                    <div class='modal-body'>
                        <div class='mb-3'>
                            <label for='edit-set-name' class='form-label'>习题集名称</label>
                            <input type='text' class='form-control' id='edit-set-name' name='update_set_name' required>
                        </div>
                        <div class='mb-3'>
                            <label for='edit-set-description' class='form-label'>描述</label>
                            <input type='text' class='form-control' id='edit-set-description' name='update_set_description'>
                        </div>
                    </div>
                    <div class='modal-footer'>
                        <button type='button' class='btn btn-secondary' data-bs-dismiss='modal'>取消</button>
                        <button type='submit' class='btn btn-primary'>保存修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 编辑章节模态框 -->
    <div class='modal fade' id='editChapterModal' tabindex='-1' aria-labelledby='editChapterModalLabel' aria-hidden='true' data-bs-backdrop='static' data-bs-keyboard='false'>
        <div class='modal-dialog fixed-center'>
            <div class='modal-content'>
                <div class='modal-header'>
                    <h5 class='modal-title' id='editChapterModalLabel'>编辑章节</h5>
                    <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='关闭'></button>
                </div>
                <form id='edit-chapter-form' method='post'>
                    <input type='hidden' name='update_chapter' value='1'>
                    <input type='hidden' name='update_chapter_id' id='edit-chapter-id'>
                    <div class='modal-body'>
                        <div class='mb-3'>
                            <label for='edit-chapter-name' class='form-label'>章节名称</label>
                            <input type='text' class='form-control' id='edit-chapter-name' name='update_chapter_name' required>
                        </div>
                        <div class='mb-3'>
                            <label for='edit-chapter-description' class='form-label'>描述</label>
                            <input type='text' class='form-control' id='edit-chapter-description' name='update_chapter_description'>
                        </div>
                    </div>
                    <div class='modal-footer'>
                        <button type='button' class='btn btn-secondary' data-bs-dismiss='modal'>取消</button>
                        <button type='submit' class='btn btn-primary'>保存修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>\n";
    
    // 使用HEREDOC添加JavaScript代码，完全避免引号嵌套问题
    $js_code = <<<JSCODE
    <script>
    // 习题集删除确认
    var delSetBtns = document.querySelectorAll('.delete-set-btn');
    for (var i=0; i<delSetBtns.length; i++) {
        delSetBtns[i].onclick = function() {
            var setId = this.getAttribute('data-set-id');
            var setName = this.getAttribute('data-set-name');
            var msg = '确定要删除习题集 "' + setName + '" 吗？删除后将无法恢复！';
            if (confirm(msg)) {
                var df = document.getElementById('delete-form');
                df.action = 'index.php?tab=exercise_sets';
                document.getElementById('delete-set-id').value = setId;
                document.getElementById('delete-type').value = 'set';
                
                // 清理旧输入
                var oldInputs = df.getElementsByTagName('input');
                for (var k=oldInputs.length-1; k>=0; k--) {
                    if (oldInputs[k].name=='delete_set' || oldInputs[k].name=='delete_chapter') {
                        df.removeChild(oldInputs[k]);
                    }
                }
                
                // 添加删除字段
                var ni = document.createElement('input');
                ni.type = 'hidden';
                ni.name = 'delete_set';
                ni.value = '1';
                df.appendChild(ni);
                df.submit();
            }
        };
    }
    
    // 章节删除确认
    var delChapterBtns = document.querySelectorAll('.delete-chapter-btn');
    for (var j=0; j<delChapterBtns.length; j++) {
        delChapterBtns[j].onclick = function() {
            var chapterId = this.getAttribute('data-chapter-id');
            var chapterName = this.getAttribute('data-chapter-name');
            var msg = '确定要删除章节 "' + chapterName + '" 吗？相关记录的章节信息将被清除。';
            if (confirm(msg)) {
                var df = document.getElementById('delete-form');
                df.action = 'index.php?tab=exercise_sets';
                document.getElementById('delete-chapter-id').value = chapterId;
                document.getElementById('delete-type').value = 'chapter';
                
                // 清理旧输入
                var oldInputs = df.getElementsByTagName('input');
                for (var k=oldInputs.length-1; k>=0; k--) {
                    if (oldInputs[k].name=='delete_set' || oldInputs[k].name=='delete_chapter') {
                        df.removeChild(oldInputs[k]);
                    }
                }
                
                // 添加删除字段
                var ni = document.createElement('input');
                ni.type = 'hidden';
                ni.name = 'delete_chapter';
                ni.value = '1';
                df.appendChild(ni);
                df.submit();
            }
        };
    }
    
    // 习题集编辑
    var editSetBtns = document.querySelectorAll('.edit-set-btn');
    var editSetModal = document.getElementById('editSetModal');
    
    // 为每个编辑习题集按钮添加点击事件
    for (var m=0; m<editSetBtns.length; m++) {
        editSetBtns[m].onclick = function() {
            var setId = this.getAttribute('data-set-id');
            var setName = this.getAttribute('data-set-name');
            var setDescription = this.getAttribute('data-set-description');
            
            // 填充表单数据
            document.getElementById('edit-set-id').value = setId;
            document.getElementById('edit-set-name').value = setName;
            document.getElementById('edit-set-description').value = setDescription || '';
            
            // 显示模态框（CSS已处理定位）
            var modal = new bootstrap.Modal(editSetModal);
            modal.show();
        };
    }
    
    // 章节编辑
    var editChapterBtns = document.querySelectorAll('.edit-chapter-btn');
    var editChapterModal = document.getElementById('editChapterModal');
    
    // 为每个编辑章节按钮添加点击事件
    for (var n=0; n<editChapterBtns.length; n++) {
        editChapterBtns[n].onclick = function() {
            var chapterId = this.getAttribute('data-chapter-id');
            var chapterName = this.getAttribute('data-chapter-name');
            var chapterDescription = this.getAttribute('data-chapter-description');
            
            // 填充表单数据
            document.getElementById('edit-chapter-id').value = chapterId;
            document.getElementById('edit-chapter-name').value = chapterName;
            document.getElementById('edit-chapter-description').value = chapterDescription || '';
            
            // 显示模态框（CSS已处理定位）
            var modal = new bootstrap.Modal(editChapterModal);
            modal.show();
        };
    };
    
    // 简化的模态框处理脚本 - 确保背景遮罩功能正常
    document.addEventListener('DOMContentLoaded', function() {
        // 为两个模态框添加显示事件监听，仅添加背景遮罩
        function ensureBackdrop(modal) {
            // 检查是否已有背景遮罩
            var existingBackdrop = document.querySelector('.modal-backdrop');
            if (!existingBackdrop) {
                // 创建背景遮罩
                var backdrop = document.createElement('div');
                backdrop.className = 'modal-backdrop fade show';
                document.body.appendChild(backdrop);
                // 添加body类
                document.body.classList.add('modal-open');
            }
        }
        
        // 为模态框添加隐藏事件监听，移除背景遮罩
        function removeBackdrop() {
            var backdrop = document.querySelector('.modal-backdrop');
            if (backdrop) {
                document.body.removeChild(backdrop);
                document.body.classList.remove('modal-open');
            }
        }
        
        // 为两个模态框绑定事件
        if (editSetModal) {
            editSetModal.addEventListener('show.bs.modal', ensureBackdrop);
            editSetModal.addEventListener('hidden.bs.modal', removeBackdrop);
        }
        
        if (editChapterModal) {
            editChapterModal.addEventListener('show.bs.modal', ensureBackdrop);
            editChapterModal.addEventListener('hidden.bs.modal', removeBackdrop);
        }
        
        // 修复背景遮罩可能在模态框显示时未正确创建的问题
        document.querySelectorAll('.modal').forEach(function(modal) {
            if (modal.classList.contains('show')) {
                ensureBackdrop(modal);
            }
        });
    });
    </script>
JSCODE;
    
    // 完全重写模态框样式
    $css_fix = "
    <style>
        /* 1. 确保背景遮罩覆盖整个视口 */
        .modal-backdrop {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100vw !important;
            height: 100vh !important;
            background-color: rgba(0, 0, 0, 0.5) !important;
            z-index: 1050 !important;
        }
        
        /* 2. 确保模态框容器正确固定定位 */
        #editSetModal, #editChapterModal {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100vw !important;
            height: 100vh !important;
            z-index: 1055 !important;
            display: none;
            overflow-x: hidden;
            overflow-y: auto;
        }
        
        /* 3. 显示状态的模态框 */
        #editSetModal.show, #editChapterModal.show {
            display: block !important;
        }
        
        /* 4. 模态框对话框 - 固定定位确保不随页面滚动 */
        #editSetModal .modal-dialog,
        #editChapterModal .modal-dialog,
        #editSetModal .modal-dialog.fixed-center,
        #editChapterModal .modal-dialog.fixed-center {
            position: fixed !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            margin: 0 !important;
            padding: 0 !important;
            z-index: 1056 !important;
            width: 100%;
            max-width: 500px;
            min-width: 300px;
            max-height: 90vh;
        }
        
        /* 5. 模态框内容 */
        #editSetModal .modal-content,
        #editChapterModal .modal-content {
            position: relative !important;
            background-color: white !important;
            border: 1px solid rgba(0, 0, 0, 0.2) !important;
            border-radius: 0.3rem !important;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5) !important;
            z-index: 1057 !important;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        /* 6. 响应式设计 */
        @media (max-width: 768px) {
            #editSetModal .modal-dialog,
            #editChapterModal .modal-dialog,
            #editSetModal .modal-dialog.fixed-center,
            #editChapterModal .modal-dialog.fixed-center {
                max-width: 90% !important;
                width: 90% !important;
            }
        }
        
        /* 7. 修复Bootstrap默认的margin */
        .modal-dialog {
            margin: 0 !important;
        }
        
        /* 8. 确保body不受影响 */
        body.modal-open {
            overflow: hidden !important;
            padding-right: 0 !important;
        }
    </style>
    ";
    
    $html .= $css_fix;
    $html .= $js_code;
    
    // 返回HTML内容
    return $html;
}